const axios = require('axios')
const fs = require('fs')
const path = require('path')

// 高德地图API配置
const AMAP_API_KEY = '64fdb23b96e7a2c0c94c95a789ecef50' // 替换为您的实际API密钥
const AMAP_API_BASE_URL = 'https://restapi.amap.com/v3'

// 获取小区边界坐标
async function getCommunityBoundary(communityName, city) {
    try {
        console.log(`正在搜索小区: ${communityName} (${city})`)

        // 搜索小区
        const searchUrl = `${AMAP_API_BASE_URL}/place/text`
        const searchParams = {
            key: AMAP_API_KEY,
            keywords: communityName,
            city: city,
            citylimit: true,
            output: 'JSON',
            offset: 1,
            page: 1,
            extensions: 'all',
        }

        const searchResponse = await axios.get(searchUrl, {
            params: searchParams,
        })
        const searchData = searchResponse.data

        if (
            searchData.status !== '1' ||
            !searchData.pois ||
            searchData.pois.length === 0
        ) {
            throw new Error(`未找到小区: ${communityName}`)
        }

        const community = searchData.pois[0]
        console.log(`找到小区: ${community.name}, ID: ${community.id}`)

        // 获取小区详情（包含边界信息）
        const detailUrl = `${AMAP_API_BASE_URL}/place/detail`
        const detailParams = {
            key: AMAP_API_KEY,
            id: community.id,
            output: 'JSON',
            extensions: 'all',
        }

        const detailResponse = await axios.get(detailUrl, {
            params: detailParams,
        })
        const detailData = detailResponse.data

        if (
            detailData.status !== '1' ||
            !detailData.pois ||
            detailData.pois.length === 0
        ) {
            throw new Error(`无法获取小区详情: ${communityName}`)
        }

        const communityDetail = detailData.pois[0]

        // 返回小区边界坐标和中心点
        return {
            name: communityDetail.name,
            id: communityDetail.id,
            location: communityDetail.location,
            shape: communityDetail.shape || null,
            address: communityDetail.address,
            city: communityDetail.cityname || city,
        }
    } catch (error) {
        console.error('获取小区边界时出错:', error.message)
        throw error
    }
}

// 使用关键字搜索楼栋
async function searchBuildingsByKeyword(communityInfo) {
    try {
        console.log('使用关键字搜索楼栋...')

        // 尝试多种关键字组合
        const keywordsList = [
            `${communityInfo.name}楼栋`,
            `${communityInfo.name}栋`,
            `${communityInfo.name}号楼`,
            `${communityInfo.name}座`,
            `${communityInfo.name}单元`,
        ]

        let allBuildings = []

        for (const keywords of keywordsList) {
            console.log(`尝试搜索关键字: ${keywords}`)

            const url = `${AMAP_API_BASE_URL}/place/text`
            const params = {
                key: AMAP_API_KEY,
                keywords: keywords,
                city: communityInfo.city,
                citylimit: true,
                output: 'JSON',
                offset: 50,
                page: 1,
                types: '120000|120100|120200|120201|120202|120203', // 住宅相关分类
            }

            try {
                const response = await axios.get(url, { params })
                const data = response.data

                if (data.status === '1' && data.pois && data.pois.length > 0) {
                    console.log(`找到 ${data.pois.length} 个相关结果`)

                    // 过滤结果，只保留与小区相关的
                    const filteredBuildings = data.pois.filter(
                        poi =>
                            poi.name.includes(communityInfo.name) ||
                            poi.address.includes(communityInfo.name)
                    )

                    allBuildings = allBuildings.concat(filteredBuildings)

                    if (filteredBuildings.length > 0) {
                        console.log(
                            `过滤后保留 ${filteredBuildings.length} 个楼栋`
                        )
                    }
                }

                // 避免请求过快
                await new Promise(resolve => setTimeout(resolve, 200))
            } catch (error) {
                console.error(`搜索关键字 ${keywords} 时出错:`, error.message)
            }
        }

        return allBuildings
    } catch (error) {
        console.error('关键字搜索时出错:', error.message)
        throw error
    }
}

// 使用多边形搜索
async function searchByPolygon(polygon, city) {
    try {
        console.log('使用多边形搜索...')

        const url = `${AMAP_API_BASE_URL}/place/polygon`
        const params = {
            key: AMAP_API_KEY,
            polygon: polygon,
            types: '120000|120100|120200|120201|120202|120203', // 住宅相关分类
            city: city,
            output: 'JSON',
            offset: 50,
            page: 1,
        }

        const response = await axios.get(url, { params })
        const data = response.data

        if (data.status !== '1') {
            console.log(`多边形搜索API返回错误: ${data.info}`)
            return []
        }

        console.log(`多边形搜索找到 ${data.pois ? data.pois.length : 0} 个结果`)
        return data.pois || []
    } catch (error) {
        console.error('多边形搜索时出错:', error.message)
        return []
    }
}

// 使用矩形区域搜索
async function searchByRectangle(bounds, city) {
    try {
        console.log('使用矩形区域搜索...')

        // 将边界转换为矩形字符串 (左下角,右上角)
        const rectangle = `${bounds[0]},${bounds[1]}|${bounds[2]},${bounds[3]}`

        const url = `${AMAP_API_BASE_URL}/place/polygon`
        const params = {
            key: AMAP_API_KEY,
            polygon: rectangle,
            types: '120000|120100|120200|120201|120202|120203', // 住宅相关分类
            city: city,
            output: 'JSON',
            offset: 50,
            page: 1,
        }

        const response = await axios.get(url, { params })
        const data = response.data

        if (data.status !== '1') {
            console.log(`矩形区域搜索API返回错误: ${data.info}`)
            return []
        }

        console.log(
            `矩形区域搜索找到 ${data.pois ? data.pois.length : 0} 个结果`
        )
        return data.pois || []
    } catch (error) {
        console.error('矩形区域搜索时出错:', error.message)
        return []
    }
}

// 主函数
async function getCommunityBuildings(communityName, city) {
    try {
        console.log(`开始获取"${communityName}"小区的楼栋信息...`)

        // 1. 获取小区边界
        const communityInfo = await getCommunityBoundary(communityName, city)
        console.log(`成功获取小区边界信息`)
        debugger

        // 2. 尝试多种搜索方法
        let allBuildings = []

        // 方法1: 关键字搜索
        const keywordBuildings = await searchBuildingsByKeyword(communityInfo)
        allBuildings = allBuildings.concat(keywordBuildings)
        debugger

        // 方法2: 多边形搜索 (如果有形状数据)
        if (communityInfo.shape) {
            const polygonBuildings = await searchByPolygon(
                communityInfo.shape,
                communityInfo.city
            )
            allBuildings = allBuildings.concat(polygonBuildings)
            debugger
        } else {
            // 方法3: 矩形区域搜索 (如果没有形状数据)
            // 创建一个以小区中心点为中心，边长约1公里的矩形区域
            const [lng, lat] = communityInfo.location.split(',').map(Number)
            const bounds = [
                lng - 0.005,
                lat - 0.005, // 左下角
                lng + 0.005,
                lat + 0.005, // 右上角
            ]

            const rectangleBuildings = await searchByRectangle(
                bounds,
                communityInfo.city
            )
            allBuildings = allBuildings.concat(rectangleBuildings)
            debugger
        }

        // 3. 去重和过滤
        const uniqueBuildings = []
        const seenIds = new Set()

        for (const building of allBuildings) {
            if (!seenIds.has(building.id)) {
                seenIds.add(building.id)
                uniqueBuildings.push(building)
            }
        }

        // 进一步过滤，确保结果与小区相关
        const filteredBuildings = uniqueBuildings.filter(
            building =>
                building.name &&
                building.location &&
                (building.name.includes(communityInfo.name) ||
                    building.address.includes(communityInfo.name) ||
                    building.name.match(/(栋|号楼|座|单元)/))
        )

        console.log(`共找到 ${filteredBuildings.length} 个楼栋`)
        debugger

        // 4. 处理结果
        const result = {
            community: {
                name: communityInfo.name,
                id: communityInfo.id,
                address: communityInfo.address,
                location: communityInfo.location,
                city: communityInfo.city,
            },
            buildings: filteredBuildings.map(building => ({
                id: building.id,
                name: building.name,
                type: building.type,
                location: building.location,
                address: building.address,
            })),
            timestamp: new Date().toISOString(),
            search_methods_used: [
                '关键字搜索',
                communityInfo.shape ? '多边形搜索' : '矩形区域搜索',
            ],
        }
        debugger

        // 5. 保存结果到文件
        const safeName = communityInfo.name.replace(
            /[^a-zA-Z0-9\u4e00-\u9fa5]/g,
            '_'
        )
        const fileName = `community_buildings_${safeName}_${Date.now()}.json`
        fs.writeFileSync(fileName, JSON.stringify(result, null, 2))
        console.log(`结果已保存到文件: ${fileName}`)

        return result
    } catch (error) {
        console.error('获取小区楼栋信息失败:', error.message)
        throw error
    }
}

// 使用示例
async function main() {
    try {
        // 替换为您要查询的小区名称和城市
        const communityName = '望京SOHO'
        const city = '北京'

        const result = await getCommunityBuildings('兴海嘉苑', '绍兴市')

        // 打印部分结果
        console.log('\n===== 楼栋列表 =====')
        result.buildings.forEach((building, index) => {
            console.log(`${index + 1}. ${building.name} - ${building.location}`)
        })
    } catch (error) {
        console.error('程序执行出错:', error.message)
    }
}

// 执行主函数
if (require.main === module) {
    main()
}

module.exports = {
    getCommunityBuildings,
}
